﻿using System;
using System.IO;

using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace SvnTools.Tasks.VersionManagement
{
	public class RevertVersionChange : Task
	{
		public ITaskItem[] AssemblyInfoFiles { get; set; }

		public ITaskItem[] DeploymentProjectFiles { get; set; }

		public override bool Execute()
		{
			if (AssemblyInfoFiles != null)
			{
				foreach (var item in AssemblyInfoFiles)
					RevertFile(item.ItemSpec, Log);
			}

			if (DeploymentProjectFiles != null)
			{
				foreach (var item in DeploymentProjectFiles)
					RevertFile(item.ItemSpec, Log);
			}

			return true;
		}

		public static void RevertFile(string filename, TaskLoggingHelper Log)
		{
			string fn_org = filename + ".vnbak";

			if( File.Exists(filename) && File.Exists(fn_org) )
			{
				Log.LogMessage(MessageImportance.Normal, "Reverting version number change: {0}", filename);

				File.Delete(filename);
				File.Move(fn_org, filename);
			}
			else if( File.Exists(filename) )
			{
				Log.LogMessage(MessageImportance.Normal, "File exists but no backup found: {0}", filename);
			}
			else if( File.Exists(fn_org) )
			{
				Log.LogMessage(MessageImportance.Normal, "Backup found (original missing), reverting: {0}", fn_org);

				File.Move(fn_org, filename);
			}
			else
			{
				Log.LogMessage(MessageImportance.Normal, "File does not exist, and no backup found: {0}", filename);
			}
		}

	}
}
